//ajax获取数据库数据
// let classid;
// let className;
function showclass(){
$.ajax({
    url: `/class/classshow`,
    type: `post`,
    success: function (data) {

        let total ='';
        //渲染表格
        data.forEach(e => {
            total += ` <tr>
    <td>${e._id}</td>
    <td>${e.name}</td>
    <td><button class="but-red delate">删除</button><button onclick="changename(event)" class="but-blue " id="change">修改</button></td>
</tr>`
        });
        $(`#classtbody`).html(total);

    }
})
}showclass();
//添加数据
$(`#box1-success`).click(function(event){
  
  let addinput=event.target.previousElementSibling.value
  console.log(addinput);
  $.ajax({
      url:`/class//addclass`,
      type: 'POST',
      data:{
         name:addinput 
      },
      success: function (data) { 
        alert(`添加成功`)
            showclass();
        }
      
  })
})
//删除数据
$(`tbody`).on('click','.delate',function(event){
    // location.reload();
    let thisname=$(this).parent().prev().prev().text();
    console.log(thisname);
    $.ajax({
        url: `/class/classdelate`,
        type: `post`,
        data: {
            _id:thisname,
        },
        success: function (data) { 
        alert(`删除成功`)
            showclass();
        }
    })
})
//修改数据
function changename(event){
    event.target.parentElement.previousElementSibling.innerHTML = '<input type="text">';
    event.target.parentElement.previousElementSibling.firstElementChild.onblur = function() { 
    console.log(this.parentElement.previousElementSibling.innerText);
    $.ajax({
        url: `/class/classchange`,
        type: `post`,
        data: { _id:this.parentElement.previousElementSibling.innerText.trim(),
            name:this.value
           
        },
        success: function (data) {   
            alert(data.mes)
        //    location.reload();     
            showclass();
        }
    }) 
   }
 
}